#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include "network.h"
#include "common.h"

void sig_child(int no) 
{
  int result;
  while ((result = waitpid(0, NULL, WNOHANG)) > 0) {}
  error_if(signal(SIGCHLD, sig_child) == SIG_ERR, "Unanable to setup signal");
}


int main() {
  int count = 0;
  struct sockaddr_in client_adress;
  int server_socket_id = server_socket_open(PORT);
  int stop = 0;
  error_if(signal(SIGCHLD, sig_child) == SIG_ERR, "Unanable to setup signal");
  while (!stop) {
    int socket_id = server_socket_accept(server_socket_id, &client_adress);
    count++;
    int result = fork();
    if (result < 0) {
      printf("Unanable to handle request, error in fork");
      error_if(close(socket_id) != -1, "Error in closing");
    } else if (result == 0) {
      printf("Received connection from %s. count=%d\n", inet_ntoa(client_adress.sin_addr), count);
      int data = htonl(count);
      int r = write(socket_id, &data, sizeof(count));
      error_if(r != sizeof(count), "Error in writing");
      error_if(close(socket_id) == -1, "Error in closing");
      stop = 1;
    }

  }
  return 0;
}

